package com.jwsoft.manager.core.integration.bigScreen.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.bigScreen.analysisXq.*;
import com.jwsoft.manager.common.vo.eduAddress.EduAddressVO;
import com.jwsoft.manager.common.vo.eduAddress.SchoolAddressQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduSchoolConfig;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollPre;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.bigScreen.AnalysisSsbmIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ApiService(funcCode = "AnalysisSsbm", title = "实时报名大屏接口")
public class AnalysisSsbmIntegrationImpl implements AnalysisSsbmIntegration {
    @Autowired
    EduSjtj03Service eduSjtj03Service;
    @Autowired
    EduHelper eduHelper;
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    EduSchoolConfigService eduSchoolConfigService;
    @Autowired
    EduSchoolService eduSchoolService;
    @Autowired
    EduAddressSchoolService eduAddressSchoolService;
    @Autowired
    EduStudentEnrollPreService eduStudentEnrollPreService;
    @Override
    public StuEnrollHzxxVO getStuEnrollHzxx(StuEnrollInVO vo) {
        StuEnrollHzxxVO hzxxvo = new StuEnrollHzxxVO();
        //报名数据
        QueryWrapper<EduStudentEnroll> qw_bm = new QueryWrapper<>();
        qw_bm.select("school_category","count(DISTINCT idcard) serial_num")
                .eq("del","0")
                .eq("year",vo.getYear())
                .in("school_category",2,3)
                .eq("area_code",vo.getAreaCode())
                .groupBy("school_category");
        List<EduStudentEnroll> li_bm= eduStudentEnrollService.list(qw_bm);
        if(!CollectionUtils.isEmpty(li_bm)){
            for(EduStudentEnroll str:li_bm){
                if("2".equals(str.getSchoolCategory())){
                    hzxxvo.setXxbmrs(str.getSerialNum());
                }else{
                    hzxxvo.setZxbmrs(str.getSerialNum());
                }
            }
        }
        //录取人数
        QueryWrapper<EduStudentEnroll> qw_lq = new QueryWrapper<>();
        qw_lq.select("DISTINCT idcard")
                .eq("del","0")
                .eq("year",vo.getYear())
                .eq("enroll_status","2")
                .in("school_category",2,3)
                .eq("area_code",vo.getAreaCode());
        List<EduStudentEnroll> li_lq= eduStudentEnrollService.list(qw_lq);
        if(!CollectionUtils.isEmpty(li_lq)){
            hzxxvo.setYlq(li_lq.size());
        }
        hzxxvo.setYbm(hzxxvo.getXxbmrs()+hzxxvo.getZxbmrs());

        //总学位数
        QueryWrapper<EduSchoolConfig> qwcon = new QueryWrapper<>();
        qwcon.select("school_category","sum(enrolment) enrolment")
                .eq("del","0")
                .eq("year",vo.getYear())
                .in("school_category",2,3)
                .eq("area_code",vo.getAreaCode())
                .groupBy("school_category");
        List<EduSchoolConfig> li_pre= eduSchoolConfigService.list(qwcon);
        int zxws = 0;//总学位数
        int xxxw = 0;//小学学位数
        int zxxw = 0;//中学学位数
        for(EduSchoolConfig convo:li_pre){
            zxws = zxws+convo.getEnrolment();
            if("2".equals(convo.getSchoolCategory())){
                xxxw=convo.getEnrolment();
            }else{
                zxxw=convo.getEnrolment();
            }
        }
        hzxxvo.setXxxws(xxxw);//小学剩余学位数 小学学位数-小学已录取报名数
        hzxxvo.setZxxws(zxxw);
        hzxxvo.setSyxw(zxws-hzxxvo.getYlq());//剩余学位数 学位数-已录取
        return hzxxvo;
    }

    @Override
    public StuEnrollXszbVO getStuEnrollXszb(StuEnrollInVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            CommonVO commonVO=new CommonVO();
            commonVO.setParamKey("area_code");
            String areaCode=commonIntegration.getValueByKey(commonVO);
            vo.setAreaCode(areaCode);
        }
        StuEnrollXszbVO serxvo = new StuEnrollXszbVO();
        int Mcount = 0;
        int Wcount = 0;
        int SchoolCategoryXx = 0;
        int SchoolCategoryZx = 0;
        QueryWrapper<EduStudentEnroll> qw_enroll_sex = new QueryWrapper<>();
        qw_enroll_sex.select("sex","count(DISTINCT idcard) serial_num")
                .eq("del","0")
                .eq("year",vo.getYear())
                .eq("area_code",vo.getAreaCode())
                .groupBy("sex");
        List<EduStudentEnroll> li_enroll_sex= eduStudentEnrollService.list(qw_enroll_sex);
        if(!CollectionUtils.isEmpty(li_enroll_sex)){
            for(EduStudentEnroll str:li_enroll_sex){
                if("1".equals(str.getSex())){
                    Mcount = Mcount+ str.getSerialNum();
                }else{
                    Wcount = Wcount+ str.getSerialNum();
                }

            }
            serxvo.setWcount(Mcount);
            serxvo.setMcount(Wcount);

        }else{
            serxvo.setWcount(0);
            serxvo.setMcount(0);
        }

        QueryWrapper<EduStudentEnroll> qw_enroll_cat = new QueryWrapper<>();
        qw_enroll_cat.select("school_category","count(DISTINCT idcard) serial_num")
                .eq("del","0")
                .eq("year",vo.getYear())
                .eq("area_code",vo.getAreaCode())
                .groupBy("school_category");
        List<EduStudentEnroll> li_enroll_cat= eduStudentEnrollService.list(qw_enroll_cat);
        if(!CollectionUtils.isEmpty(li_enroll_cat)){
            for(EduStudentEnroll str:li_enroll_cat){
                if("2".equals(str.getSchoolCategory())){
                    SchoolCategoryXx = SchoolCategoryXx+str.getSerialNum();
                }else{
                    SchoolCategoryZx = SchoolCategoryZx+str.getSerialNum();
                }
            }
            serxvo.setSchoolCategoryZx(SchoolCategoryZx);
            serxvo.setSchoolCategoryXx(SchoolCategoryXx);
        }else{
            serxvo.setSchoolCategoryZx(0);
            serxvo.setSchoolCategoryXx(0);
        }
        return serxvo;
    }

    @Override
    public StuEnrollBmrsVO getStuEnrollBmrs(StuEnrollInVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            CommonVO commonVO=new CommonVO();
            commonVO.setParamKey("area_code");
            String areaCode=commonIntegration.getValueByKey(commonVO);
            vo.setAreaCode(areaCode);
        }
        StuEnrollBmrsVO bmrsvo = new StuEnrollBmrsVO();
        QueryWrapper<EduStudentEnroll> qw_enroll = new QueryWrapper<>();
        qw_enroll.select("source","count(DISTINCT idcard) serial_num")
                .eq("Del", 0)
                .eq("year", vo.getYear())
                .eq("area_code",vo.getAreaCode());
        if(!ObjectUtils.isEmpty(vo.getSchoolCategory())){
            qw_enroll.eq("school_category",vo.getSchoolCategory());
        }
        qw_enroll.groupBy("source");
        List<EduStudentEnroll> l1 = eduStudentEnrollService.list(qw_enroll);
        int xs = 0;
        int xx = 0;
        if(!CollectionUtils.isEmpty(l1)){
            for(EduStudentEnroll str:l1){
                if("2".equals(str.getSource())){
                    xs = xs+str.getSerialNum();
                }else{
                    xx = xx+str.getSerialNum();
                }
            }
        }
        bmrsvo.setXsbm(xs);
        bmrsvo.setXxbm(xx);
        //实时报名人数趋势
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dt = formatter.format(date);
        List<StuEnrollBmqsVO> bmqsList = new ArrayList<>();
        QueryWrapper<EduStudentEnroll> qw_enroll_jt = new QueryWrapper<>();
        qw_enroll_jt.select("HOUR(create_time) as create_name","count(DISTINCT idcard) as year")
                .eq("Del", 0)
                .eq("year", vo.getYear())
                .eq("area_code",vo.getAreaCode())
                .eq("date_format(create_time,'%Y%m%d')",dt);
        if(!ObjectUtils.isEmpty(vo.getSchoolCategory())){
            qw_enroll_jt.eq("school_category",vo.getSchoolCategory());
        }
        qw_enroll_jt.groupBy("HOUR(create_time)");
        List<EduStudentEnroll> l1_jt = eduStudentEnrollService.list(qw_enroll_jt);
        for(EduStudentEnroll en:l1_jt){
            StuEnrollBmqsVO svo = new StuEnrollBmqsVO();
            svo.setXzhou(en.getCreateName());
            svo.setYzhou(en.getYear());
            bmqsList.add(svo);
        }
        bmrsvo.setBmqsList(bmqsList);
        return bmrsvo;
    }

    @Override
    public List<StuEnrollXzjdpmVO> getStuEnrollXzjdpm(StuEnrollInVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            CommonVO commonVO=new CommonVO();
            commonVO.setParamKey("area_code");
            String areaCode=commonIntegration.getValueByKey(commonVO);
            vo.setAreaCode(areaCode);
        }
        List<StuEnrollXzjdpmVO> stuEnrollXzjdpmVO=eduStudentEnrollService.getStuEnrollXzjdpmVO(vo);
        return stuEnrollXzjdpmVO.subList(0,Math.min(stuEnrollXzjdpmVO.size(),5));
    }

    @Override
    public StuEnrollDgxxVO getStuEnrollDgxx(StuEnrollDgxxInVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getSchoolId())){
            throw new AppException("学校ID不能为空");
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            CommonVO commonVO=new CommonVO();
            commonVO.setParamKey("area_code");
            String areaCode=commonIntegration.getValueByKey(commonVO);
            vo.setAreaCode(areaCode);
        }
        StuEnrollDgxxVO dgxxvo = new StuEnrollDgxxVO();
        EduSchoolVO school = eduSchoolService.getDetail(vo.getSchoolId());
        if(!ObjectUtils.isEmpty(school)){
            dgxxvo.setSchoolNature(school.getSchoolNature());
            dgxxvo.setSchoolName(school.getSchoolName());
            dgxxvo.setSchoolCategory(school.getSchoolCategory());
        }
        SchoolAddressQueryVO saqvo = new SchoolAddressQueryVO();
        saqvo.setSchoolId(vo.getSchoolId());
        List<EduAddressVO> scaddressList =  eduAddressSchoolService.getAddress(saqvo);
        if(!CollectionUtils.isEmpty(scaddressList)){
            dgxxvo.setAddressName(scaddressList.get(0).getAddressName());
        }
        dgxxvo.setSchoolId(vo.getSchoolId());
        //已报名
        if (vo.getPageNum() == null || vo.getPageSize() == null || vo.getPageSize() == 0) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(10);
        }else{
            vo.setPageNum(vo.getPageNum()+1);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduStudentEnroll> qw_bm = new QueryWrapper<>();
        qw_bm.select("enroll_status","config_name","full_name","idcard","sex","birth_ymd","address")
                .eq("del","0")
                .eq("year",vo.getYear())
                .eq("school_id",vo.getSchoolId())
                .in("school_category",2,3)
                .eq("area_code",vo.getAreaCode());
        List<EduStudentEnroll> li_bm= eduStudentEnrollService.list(qw_bm);
        dgxxvo.setYbm(li_bm.size());
        int ylq = 0;
        if(!CollectionUtils.isEmpty(li_bm)){
            Map<String,Long> map = li_bm.stream().filter(item-> StringUtil.isNotBlank(item.getEnrollStatus())).collect(Collectors.groupingBy(EduStudentEnroll::getEnrollStatus,Collectors.counting()));
            if(!ObjectUtils.isEmpty(map)){
                for(String key : map.keySet()){
                    if("2".equals(key)){
                        //已录取
                        ylq = ylq+map.get(key).intValue();
                    }
                }
            }
        }
        //计划招生人数
        QueryWrapper<EduSchoolConfig> qwcon = new QueryWrapper<>();
        qwcon.select("sum(enrolment) enrolment")
                .eq("del","0")
                .eq("year",vo.getYear())
                .eq("school_id",vo.getSchoolId())
                .in("school_category",2,3)
                .eq("area_code",vo.getAreaCode());
        Map<String, Object> map = eduSchoolConfigService.getMap(qwcon);
        if (!ObjectUtils.isEmpty(map)) {
            dgxxvo.setJhzsrs(Integer.valueOf(map.get("enrolment").toString()));
        }else{
            dgxxvo.setJhzsrs(0);
        }
        //剩余学位
        dgxxvo.setSyxw(dgxxvo.getJhzsrs()-ylq);
        //预报名人数
        QueryWrapper<EduStudentEnrollPre> qw_befor = new QueryWrapper<>();
        qw_befor.select("year")
                .eq("del","0")
                .eq("school_id",vo.getSchoolId())
                .in("year",vo.getYear(),vo.getYear()-1)
                .eq("area_code",vo.getAreaCode());
        List<EduStudentEnrollPre> li_befor = eduStudentEnrollPreService.list(qw_befor);
        dgxxvo.setYbmrs(li_befor.size());
        //报名学生明细 31
        List<StuEnrollBmmxVO> bmmxList = new ArrayList<>();
        for(EduStudentEnroll esevo : li_bm){
            StuEnrollBmmxVO bmmxVO = new StuEnrollBmmxVO();
            bmmxVO.setConfigName(esevo.getConfigName());
            bmmxVO.setFullName(esevo.getFullName());
            bmmxVO.setSex(esevo.getSex());
            bmmxVO.setIdcard(esevo.getIdcard());
            //年龄
            String csrq = esevo.getBirthYmd();
            LocalDate date1 = LocalDate.now();
            DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
            String dqrq = date1.format(formatter1);
            int nl1 = Integer.parseInt(StringUtils.substring(dqrq,0,4))-Integer.parseInt(StringUtils.substring(csrq,0,4));
            int nl2 = Integer.parseInt(StringUtils.substring(dqrq,4,6))-Integer.parseInt(StringUtils.substring(csrq,4,6));
            if(nl2>=0){
                bmmxVO.setNl(nl1);
            }else{
                bmmxVO.setNl(nl1-1);
            }
            //地址
            bmmxVO.setAddress(esevo.getAddress());
            bmmxList.add(bmmxVO);
        }

        PageInfo<StuEnrollBmmxVO> pageInfo = new PageInfo<>(bmmxList.subList(0,Math.min(bmmxList.size(),10)));
        dgxxvo.setBmmxList(pageInfo.getList());

        return dgxxvo;
    }

}
